<?php

function village_plant_add_page() {
    return drupal_get_form('village_plant_edit_form');
}

function village_plant_edit_page($id) {
    return drupal_get_form('village_plant_edit_form', $id,"edit");
}

function village_plant_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = village_plant_load($id);
//        $form['addr_id'] = $id;
        if (empty($record)) {
            drupal_set_message(t('村落不存在！'), 'status', FALSE);
        }
    }
//    $plant_disabled = $form_state['build_info']['args'][1] == "add"?false:true;
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, FALSE,  !empty($record) ? $record->addr_id:'','');
    $form['plant'] = _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');

    $form['area'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积',
        '#default_value' => !empty($record) ? $record->area : '',
        '#required' => TRUE,
    );
    $form['acre_yield'] = array(
        '#type' => 'textfield',
        '#title' => '亩产量（千克/亩）',
        '#default_value' => !empty($record) ? $record->acre_yield : '',
        '#required' => TRUE,
    );
    $form['price'] = array(
        '#type' => 'textfield',
        '#title' => '价格（元/千克）',
        '#default_value' => !empty($record) ? $record->price : '',
        '#required' => TRUE,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => village_plant_edit_form_submit_access($form_state, $id),
    );
    return $form;
}

function village_plant_edit_form_validate($form, &$form_state) {
    $validate = true;
    if(!empty($form_state['values']['address_fuzzy'])){
        $addr_object = addr_load_by_full_name($form_state['values']['address_fuzzy']);
        if(empty($addr_object)){
            form_set_error('address_fuzzy', '请根据提示输入正确（完整）的地址信息');
            $validate = false;
        }elseif($addr_object->geo_level !== "5"){
            form_set_error('address_fuzzy', '请根据提示输入村落地址信息');
        }

    }else if(empty($form_state['values']['village'])){
        form_set_error('village', '必须填写 地址,输入地址或点选省市县乡镇村地址，两种方式任选其一');
        $validate = false;
    }
    if(!empty($form_state['values']['area'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['area']) || (strlen(explode('.',$form_state['values']['area'])[0])>8)) {
            form_set_error('area', "种植面积格式错误");
        }
    }
    if(!empty($form_state['values']['acre_yield'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['acre_yield']) || (strlen(explode('.',$form_state['values']['acre_yield'])[0])>8)) {
            form_set_error('acre_yield',  "亩产量格式错误");
        }
    }
    if(!empty($form_state['values']['price'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['price']) || (strlen(explode('.',$form_state['values']['price'])[0])>8)) {
            form_set_error('price',  "价格格式错误");
        }
    }
    if(empty($form_state['values']['plant'])){
        form_set_error('plant', '必须填写 农作物');
    }else if(empty($form_state['build_info']['args'][0])&&$validate){
        $record = db_select('village_plant', 'u')
            ->condition('u.addr_id', _get_address_id_from_autocomplete_select($form_state))
            ->condition('u.plant_id', get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false))
            ->fields('u')
            ->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('plant', "村落该种植信息已存在！");
        }
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
        }
    }
}

function village_plant_edit_form_submit($form, &$form_state) {
    global $user;

    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    if (empty($id)) { //add new village_plant
        $nid = db_insert('village_plant') // Table name no longer needs {}
                ->fields(array(
                    'addr_id' => $address,
                    'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                    'area' => $form_state['values']['area'],
                    'acre_yield' => $form_state['values']['acre_yield'],
                    'price' => $form_state['values']['price'],
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }

    } else {
        $nid = db_update('village_plant')// edit exsting store. todo: update only modified fields
        ->fields(array(
            'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
            'area' => $form_state['values']['area'],
            'acre_yield' => $form_state['values']['acre_yield'],
            'price' => $form_state['values']['price'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->condition('village_plant_id', $id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }

    }
}

function village_plant_edit_form_submit_access(&$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if ($id) {
        //edit
        $village_plant = village_plant_load($id);
        if ($village_plant) {
            $user_info = _get_user_info($user->uid);
            if ($village_plant->author_uid == $user->uid && user_access('edit own village_plant') || user_access('edit all village_plant')) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            //load false
            drupal_set_message(t('村落活动不存在！'), 'status', FALSE);
            return FALSE;
        }
    } else {
        //add
        return user_access('add village');
    }

}

function village_plant_load($id) {
    $result = db_select('village_plant', 'R')
        -> fields('R')
        -> condition('R.village_plant_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}

